package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ArticleDto;
import com.heima.model.common.pojos.search.SearchArticleDoc;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author Lijx
 * @Date 2024-07-29 19:37
 */
@Component
@Slf4j
public class SyncArticleListener {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @KafkaListener(topics = "save_into_es")
    public void saveArticle(String msg) {
        log.info("接收到更新ES索引库文章信息，消息为：{}", msg);
        try {
            //1、解析接收到信息
            ArticleDto articleDto = JSON.parseObject(msg, ArticleDto.class);
            //转为文档类型
            SearchArticleDoc articleDoc = new SearchArticleDoc(articleDto);

            //2、创建Request对象
            IndexRequest request = new IndexRequest("app_info_article").id(articleDoc.getId().toString());
            //准备Json文档
            request.source(JSON.toJSONString(articleDoc), XContentType.JSON);

            //3、发送请求：新增文章文档信息
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("sync es error={}",e);
        }
    }
}
